import axios from 'axios'
import vuex from '@/store/index'
import { Message } from 'element-ui'

export function request(url, params) {
  const instance = axios.create({
    baseURL: '/api',
    timeout: 30000, // 30秒超时
    withCredentials: true // 开启跨域
  })
  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      return config
    },
    (err) => {
      console.log(err)
    }
  )
  // 响应拦截器
  instance.interceptors.response.use(
    (config) => {
      const code = config.data.code
      if (code !== 200 && !(code >= 800 && code <= 803)) {
        Message.error(config.data.message || '未知错误')
      }

      return config
    },
    (err) => {
      console.log([err])
      if (err.response.data.msg === '需要登录') {
        return (vuex.state.isLogin = false)
      } else {
        return Message.error(err.response.data.message || '未知错误')
      }
    }
  )
  instance.defaults.withCredentials = true
  // 所有请求都是get
  if (params) {
    const query = { params }
    return instance.get(url, query)
  } else {
    return instance.get(url)
  }
}
